import { AddressType, LAST_ADDRESS_STORE_KEY } from '@/dataTransfer/location';
import pClose from '@/images/common/circleClose.png';
import pLocation from '@/images/common/location.png';
import pChecked from '@/images/common/redChecked.png';
import { Image, Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React from 'react';
import { AtFloatLayout } from 'taro-ui';
import 'taro-ui/dist/style/components/float-layout.scss';
import './index.scss';

const AddressSelect = ({
  isOpened,
  handleClose,

  allAddresses = [],
  selectedAddress = {},
}) => {
  const handleCheck = (address) => {
    handleClose(address);

    // 存储上次选择的ID
    if (address.id) {
      Taro.setStorage({ key: LAST_ADDRESS_STORE_KEY, data: address.id });
    }
  };

  const handleAddBtn = () => {
    Taro.navigateTo({ url: '/giftCardSubPack/addAddress/index' });
  };

  return (
    <View catchMove>
      <AtFloatLayout
        isOpened={isOpened}
        scrollY
        onClose={() => {
          handleClose();
        }}
        className="addressSelect"
      >
        <View className="addressContent">
          <Image
            className="closeIcon"
            src={pClose}
            onClick={() => {
              handleClose();
            }}
          />
          <View className="ncenter header">配送至</View>
          {[AddressType.gps, AddressType.ip].includes(selectedAddress.type) && (
            <View className="ncenter item" key="addr_location">
              <Image className="checkIcon" src={pLocation} />
              <Text className={['txt', 'active'].join(' ')}>{selectedAddress.address}</Text>
            </View>
          )}
          {allAddresses?.map((addr, index) => (
            <View
              className="ncenter item addrLine"
              onClick={() => handleCheck(addr)}
              key={'addr_' + index}
            >
              <Image
                className="checkIcon"
                src={addr.id == selectedAddress.id ? pChecked : ''}
              ></Image>
              <Text className={['txt', selectedAddress.id == addr.id && 'active'].join(' ')}>
                {addr.address + addr.houseNumber}
              </Text>
            </View>
          ))}
          <View className={Taro.$bottomHight ? 'lineEndH' : 'lineEnd'}></View>
          <View className="bottom">
            <View className="ncenter btn customePageBackgroundStyle" onClick={handleAddBtn}>
              新增地址
            </View>
            <View className={Taro.$bottomHight ? 'bottomH' : 'bottom0'}></View>
          </View>
        </View>
      </AtFloatLayout>
    </View>
  );
};

export default AddressSelect;
